/**
 * Created by Good luck on 2017/3/20.
 */
var COUNT = 4;
var board = new Array();
var hasConflicted = new Array();
var score = 0;
var cellSideLength;
var cellSpace;
var length;
var randx;
var randy;
var stop;
var time_state=false;
$(document).ready(function () {

    length = documentWidth > 500 ? window.innerHeight * 0.6 : documentWidth * 0.92;
    if (localStorage.count !== null) {
        COUNT = localStorage.count;
    }
    newGame();
    $("#start").click(function () {
        // alert($("#count").val());
        localStorage.count = ($("#count").val() < 50 && $("#count").val()) > 0 ? parseInt($("#count").val()) : 4;
        location.reload();
    })

});
function newGame() {

    score=0;
    updateScore(score);
    document.getElementById("time").innerText = "00:00";
    time_fun();
    init();

};

function init() {
    creatArray(COUNT);
    InitPanel(length);
    InitTitle(length);
    InitCell(length);

    updateBoardView();
    generateRandNumber();
    generateRandNumber();
}

/**
 * 创建数组
 * @param COUNT
 */
function creatArray(COUNT) {
    for (var i = 0; i < COUNT; i++) {
        board[i] = new Array();
        hasConflicted[i] = new Array();
        for (var j = 0; j < COUNT; j++) {
            board[i][j] = 0;
            hasConflicted[i][j] = false;
        }
    }
}

function updateBoardView() {
    $(".number-cell").remove();
    for (var i = 0; i < COUNT; i++)
        for (var j = 0; j < COUNT; j++) {
            $(".container").append('<div class="number-cell" id="number-cell-' + i + '-' + j + '"></div>');
            var theNumberCell = $('#number-cell-' + i + '-' + j);
            theNumberCell.css('width', cellSideLength);
            theNumberCell.css('height', cellSideLength);
            theNumberCell.css('top', getPosTop(i, j, cellSpace, cellSideLength));
            theNumberCell.css('left', getPosLeft(i, j, cellSpace, cellSideLength));
            theNumberCell.css('background-color', getNumberBackgroundColor(board[i][j]));
            theNumberCell.css('color', getNumberColor(board[i][j]));
            theNumberCell.text(board[i][j] == 0 ? null : board[i][j]);
            hasConflicted[i][j] = false;
        }
    $('.number-cell').css('line-height', cellSideLength + "px");
    $('.number-cell').css('font-size', 0.3 * cellSideLength + "px");
    $('.number-cell').css('border-radius', 0.02 * cellSideLength);

}

/**
 * 返回false，说明应景没有空位，返回true说明已经随机生成
 * @returns {boolean}
 */
function generateRandNumber() {
    if (checkNull(board)) {
        return false;
    }
    randx = parseInt(Math.floor((Math.random() * COUNT)));
    randy = parseInt(Math.floor((Math.random() * COUNT)));
    var time = 0;
    while (time < 40) {
        if (board[randx][randy] == 0)
            break;
        randx = parseInt(Math.floor((Math.random() * COUNT)));
        randy = parseInt(Math.floor((Math.random() * COUNT)));
        time++;
    }
    if (time == 50) {
        for (var i = 0; i < COUNT; i++) {
            for (var j = 0; j < COUNT; j++) {
                if (board[i][j] == 0) {
                    randx = i;
                    randy = j;
                }
            }
        }
    }
    //随机生成呢个一个数字
    var randNumber = Math.random() < 0.8 ? 2 : 4;
    //在随机位置显示数字
    board[randx][randy] = randNumber;

    showNumberWithAnimation(randx, randy, randNumber);
    return true;
}

function followCheckFinish() {
    setTimeout("generateRandNumber()", 210);
    setTimeout("isGameOver()", 300);
}

function moveToLeft() {
    if (moveLeft()) {
        followCheckFinish();
    }
}
function moveToUp() {
    if (moveUp()) {
        followCheckFinish();
    }
}
function moveToRight() {
    if (moveRight()) {
        followCheckFinish();
    }
}
function moveToDown() {
    if (moveDown()) {
        followCheckFinish();
    }
}

$(document).keydown(function (event) {
    if (event.keyCode > 36 && event.keyCode < 41) {
        event.preventDefault();
    }//阻止默认的效果
    switch (event.keyCode) {
        //left
        case 37:
            moveToLeft();
            break;
        //    up
        case 38:
            moveToUp();
            break;
        //    right
        case 39:
            moveToRight();
            break;
        //    down
        case 40:
            moveToDown();
            break;
        default:
            break;
    }
});

function moveLeft() {
    if (!canMoveLeft(board)) {
        return false;
    }

    // moveLeft;
    for (var i = 0; i < COUNT; i++) {
        for (var j = 1; j < COUNT; j++) {
            if (board[i][j] != 0) {
                for (var k = 0; k < j; k++) {
                    if (board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
                        //followCheckFinish
                        showMoveAnimation(i, j, i, k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;

                    }
                    else if (board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]) {
                        //followCheckFinish
                        showMoveAnimation(i, j, i, k);
                        //    add
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        score += board[i][k];
                        updateScore(score);
                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()", 200);
    return true;
}

function moveRight() {
    if (!canMoveRight(board))
        return false;

    //moveRight
    for (var i = 0; i < COUNT; i++)
        for (var j = COUNT - 2; j >= 0; j--) {
            if (board[i][j] != 0) {
                for (var k = COUNT - 1; k > j; k--) {

                    if (board[i][k] == 0 && noBlockHorizontal(i, j, k, board)) {
                        showMoveAnimation(i, j, i, k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if (board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board) && !hasConflicted[i][k]) {
                        showMoveAnimation(i, j, i, k);
                        board[i][k] *= 2;
                        board[i][j] = 0;
                        score += board[i][k];
                        updateScore(score);
                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()", 200);
    return true;
}

function moveUp() {

    if (!canMoveUp(board))
        return false;

    //moveUp
    for (var j = 0; j < COUNT; j++)
        for (var i = 1; i < COUNT; i++) {
            if (board[i][j] != 0) {
                for (var k = 0; k < i; k++) {

                    if (board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
                        showMoveAnimation(i, j, k, j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if (board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasConflicted[k][j]) {
                        showMoveAnimation(i, j, k, j);
                        board[k][j] *= 2;
                        board[i][j] = 0;
                        score += board[k][j];
                        updateScore(score);
                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()", 200);
    return true;
}

function moveDown() {
    if (!canMoveDown(board))
        return false;

    //moveDown
    for (var j = 0; j < COUNT; j++)
        for (var i = COUNT - 2; i >= 0; i--) {
            if (board[i][j] != 0) {
                for (var k = COUNT - 1; k > i; k--) {

                    if (board[k][j] == 0 && noBlockVertical(j, i, k, board)) {
                        showMoveAnimation(i, j, k, j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if (board[k][j] == board[i][j] && noBlockVertical(j, i, k, board) && !hasConflicted[k][j]) {
                        showMoveAnimation(i, j, k, j);
                        board[k][j] *= 2;
                        board[i][j] = 0;
                        score += board[k][j];
                        updateScore(score);
                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()", 200);
    return true;
}

function gameOver() {
    stop_time();
    document.getElementById("time").innerText = "00:00";
    alert("游戏结束 分数为"+score);
    score=0;
    updateScore(score);
}
function noMove(board) {
    // if (canMoveDown(board) || canMoveLeft(board) || canMoveRight(board) || canMoveUp(board))
    //     return false;
    // return true;
    //-------------------------------------------------------------------------------------------
    return !(canMoveDown(board) || canMoveLeft(board) || canMoveRight(board) || canMoveUp(board));
}
function isGameOver() {
    if (checkNull(board) && noMove(board)) {
        gameOver();
    }
}

document.addEventListener('touchstart', function (event) {
    startX = event.touches[0].pageX;
    startY = event.touches[0].pageY;
});
document.addEventListener('touchmove', function (event) {
    event.preventDefault();
});

document.addEventListener('touchend', function (event) {
    endX = event.changedTouches[0].pageX;
    endY = event.changedTouches[0].pageY;
    var deltax = endX - startX;
    var deltay = endY - startY;

    if (Math.abs(deltax) < 0.3 * documentWidth && Math.abs(deltay) < 0.3 * documentWidth) {
        return;
    }
    if (Math.abs(deltax) > Math.abs(deltay)) {
        //    在x方向
        // if (deltax > 0) {
        //     moveToRight();
        //
        // } else {
        //     moveToLeft();
        // }
        //---------------------------------------------------------------------------
        (deltax > 0) ? moveToRight() : moveToLeft();
        //---------------------------------------------------------------------------
    } else {
        //    在y方向
        // if (deltay > 0) {
        //     moveToDown();
        // } else {
        //     moveToUp();
        // }
        //---------------------------------------------------------------------------
        (deltay > 0) ? moveToDown() : moveToUp();
        //---------------------------------------------------------------------------
    }

});
